import { h, onMounted, reactive, type Ref, ref, toRaw } from "vue";
import type { FormItemProps } from "@/views/learn/chapters/utils/types";
import editForm from "@/views/learn/chapters/form.vue";
import chaptersPlayer from "@/views/learn/chapters/chaptersPlayer.vue";
import dayjs from "dayjs";
import type { PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
import {
  chaptersAdd,
  chaptersDel,
  chaptersUpdate,
  getChaptersList
} from "@/api/learn/chapters";
import { addDialog } from "@/components/ReDialog/index";
import { deviceDetection } from "@pureadmin/utils";
import { getCategoryAllList } from "@/api/learn/category";

export default function useChapters(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    courseId: "",
    title: "",
    pageSize: 10,
    currentPage: 1
  });
  const loading = ref(true);
  const isShow = ref(false);
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeData = ref([]);
  // tree
  const treeLoading = ref(true);

  async function onTreeSelect({ id, selected }) {
    form.courseId = selected ? id : "";
    await onSearch();
  }

  function onBaseClick(row) {
    addDialog({
      title: `标题：${row.title}`,
      hideFooter: true,
      props: {
        formInline: {
          courseId: form.courseId || row?.courseId || "",
          id: row?.id || "",
          title: row?.title || "",
          content: row?.content || "",
          rank: row?.rank || 99,
          video: row?.video || ""
        }
      },
      width: "70%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(chaptersPlayer, { ref: formRef })
    });
  }

  // 表格列
  const columns: TableColumnList = [
    {
      label: "标题",
      prop: "title"
    },
    {
      label: "内容",
      prop: "content"
    },
    {
      label: "课程视频",
      prop: "video",
      cellRenderer: ({ row }) => {
        return <span onClick={() => onBaseClick(row)}>{row.video}</span>;
      }
    },
    {
      label: "创建时间",
      prop: "createdAt",
      formatter: ({ createdAt }) => dayjs(createdAt).format("YYYY-MM-DD")
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ];

  // 分页
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 查询列表
  async function onSearch() {
    loading.value = true;
    const { data } = await getChaptersList(toRaw(form));
    dataList.value = data.lists;
    pagination.total = data.pagination.total;
    pagination.pageSize = data.pagination.pageSize;
    pagination.currentPage = data.pagination.currentPage;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // 重置
  async function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    form.courseId = "";
    treeRef.value.onTreeReset();
    await onSearch();
  }

  // 新增 修改
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (title === "新增" && !form.courseId) {
      message("请选择课程", { type: "warning" });
      return;
    }
    addDialog({
      title: `${title}章节`,
      props: {
        formInline: {
          courseId: form.courseId || row?.courseId || "",
          id: row?.id || "",
          title: row?.title || "",
          content: row?.content || "",
          rank: row?.rank || 99,
          video: row?.video || "",
          fileList: row?.fileList || []
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        async function chores() {
          message(`您${title}了名称为${curData.title}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          await onSearch(); // 刷新表格数据
        }

        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              let { data } = await chaptersAdd(curData);
              await formRef.value.getUploadRef().upload({
                businessId: data.id
              });
              await chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              await chaptersUpdate(Object.assign(curData, { id: curData.id }));
              await formRef.value.getUploadRef().upload();
              await chores();
            }
          }
        });
      }
    });
  }

  // 删除
  async function handleDelete(row) {
    await chaptersDel({ id: row.id });
    message(`您删除了名称为${row.title}的这条数据`, { type: "success" });
    await onSearch();
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  // handle pageSize
  async function handleSizeChange(val: number) {
    form.pageSize = val;
    await onSearch();
  }

  // handle currentPage
  async function handleCurrentChange(val: number) {
    form.currentPage = val;
    await onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  onMounted(async () => {
    // treeLoading.value = true;
    const { data } = await getCategoryAllList();
    const list = data.lists.map(item => {
      return {
        id: item.id,
        label: "分类：" + item.name,
        children: item.courses.map(course => {
          return {
            id: course.id,
            label: "课程：" + course.name
          };
        })
      };
    });
    treeData.value = list;
    await onSearch();
    treeLoading.value = false;
  });

  return {
    onTreeSelect,
    treeLoading,
    treeData,
    form,
    isShow,
    columns,
    loading,
    openDialog,
    onSearch,
    rowStyle,
    dataList,
    pagination,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange,
    handleDelete,
    resetForm,
    onBaseClick
  };
}
